package com.xgr.wonderful.adapter;

import java.util.Date;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.DateUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.view.CircleImageView;
import com.xgr.wonderful.MyApplication;
import com.xgr.wonderful.R;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ChatMsgAdapter extends BaseAdapter {
	
	private final String TAG ="ChatMsgAdapter" ;
	
	private final int MSG_TYPE_RECV_TXT =0;
	private final int MSG_TYPE_SENT_TXT =1;
	
	private EMConversation mConversation;
	private Context mContext;
	private User remoteUser;
	private LayoutInflater mInflater;
	//private SuperConversation mSuperConversation;

	public ChatMsgAdapter(Context context, User remoteUser) {
		// TODO Auto-generated constructor stub
		this.mContext = context;
		this.remoteUser = remoteUser;
		this.mConversation = EMChatManager.getInstance().getConversation(
				remoteUser.getID().toString());
		this.mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mConversation.getMsgCount();
	}

	@Override
	public EMMessage getItem(int position) {
		// TODO Auto-generated method stub
		return mConversation.getMessage(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}
	@Override
	public int getItemViewType (int position ){
		EMMessage message = mConversation.getMessage(position) ;
		if (message.direct== EMMessage.Direct.RECEIVE){
				return MSG_TYPE_RECV_TXT ;
			}else {
				return MSG_TYPE_SENT_TXT ;
			}
	}
	
	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return 2;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final EMMessage message = getItem(position);
		TextMessageBody textMessageBody = (TextMessageBody) message.getBody();
		RecvViewHolder recvViewHolder = null;
		SendViewHolder sendViewHolder = null;
		if (getItemViewType(position) == MSG_TYPE_RECV_TXT) {
			//接收消息
			recvViewHolder = new RecvViewHolder();
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_received_message, null);
				recvViewHolder.mAvatar = (CircleImageView) convertView
						.findViewById(R.id.iv_userhead);
				recvViewHolder.mContent = (TextView) convertView
						.findViewById(R.id.tv_chatcontent);
				recvViewHolder.mTime = (TextView) convertView
						.findViewById(R.id.timestamp);
				convertView.setTag(recvViewHolder);
			} else {
				recvViewHolder = (RecvViewHolder)convertView.getTag();
			}
			recvViewHolder.mContent.setText(textMessageBody.getMessage());
			ImageLoader.getInstance().displayImage(
					remoteUser.getPhoto()!= null? remoteUser.getPhoto().getSmall(): null,
					recvViewHolder.mAvatar ,
					MyApplication.getInstance().getOptions(R.drawable.user_icon_default) ,
					new SimpleImageLoadingListener());
		} else {
			//发送的消息
			sendViewHolder = new SendViewHolder();
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.item_sent_message, null);
				sendViewHolder.mAvatar = (CircleImageView) convertView
						.findViewById(R.id.iv_userhead);
				sendViewHolder.mContent = (TextView) convertView
						.findViewById(R.id.tv_chatcontent);
				sendViewHolder.mProgressBar = (ProgressBar) convertView
						.findViewById(R.id.pb_sending);
				sendViewHolder.mStatus = (ImageView) convertView
						.findViewById(R.id.msg_status);
				sendViewHolder.mTime = (TextView) convertView
						.findViewById(R.id.timestamp);
				convertView.setTag(sendViewHolder);
			} else {
				sendViewHolder = (SendViewHolder) convertView.getTag();
			}
			sendViewHolder.mContent.setText(textMessageBody.getMessage());
			ImageLoader.getInstance().displayImage(
					LocalUserUtils.getInstance().getLocalUserPhoto()== null ? null:
						LocalUserUtils.getInstance().getLocalUserPhoto().getSmall(),
					sendViewHolder.mAvatar,
					MyApplication.getInstance().getOptions(R.drawable.user_icon_default) ,
					new SimpleImageLoadingListener());
			switch (message.status) {
			case SUCCESS: // 发送成功
				sendViewHolder.mProgressBar.setVisibility(View.GONE);
				sendViewHolder.mStatus.setVisibility(View.GONE);
				break;
			case FAIL: // 发送失败
				sendViewHolder.mProgressBar.setVisibility(View.GONE);
				sendViewHolder.mStatus.setVisibility(View.VISIBLE);
				break;
			case INPROGRESS: // 发送中
				sendViewHolder.mProgressBar.setVisibility(View.VISIBLE);
				sendViewHolder.mStatus.setVisibility(View.GONE);
				break;
			default:
				// 发送消息
				sendMsgInBackground(message, sendViewHolder);
			}
			//相当于是再次发送
			sendViewHolder.mStatus.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					//CREATE创建 成功，是再次发送？
					message.status = EMMessage.Status.CREATE;
					notifyDataSetChanged();
				}
			});
		}
		TextView timeView = (recvViewHolder != null ? recvViewHolder.mTime : sendViewHolder.mTime);
		if (position == 0) {
			timeView.setText(DateUtils.getTimestampString(new Date(
					message.getMsgTime())));
			timeView.setVisibility(View.VISIBLE);
		} else {
			// 两条消息时间离得如果稍长，显示时间
			if (DateUtils.isCloseEnough(message.getMsgTime(), mConversation
					.getMessage(position - 1).getMsgTime())) {
				timeView.setVisibility(View.GONE);
			} else {
				timeView.setText(DateUtils.getTimestampString(new Date(
						message.getMsgTime())));
				timeView.setVisibility(View.VISIBLE);
			}
		}
		return convertView;
	}
	
	/*
	 * 相当于正在发送中
	 */
	public void sendMsgInBackground(EMMessage message,
			SendViewHolder viewHolder) {
		viewHolder.mStatus.setVisibility(View.GONE);
		viewHolder.mProgressBar.setVisibility(View.VISIBLE);

		EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
			@Override
			public void onSuccess() {
				updateSendedView();
			}

			@Override
			public void onError(int code, String error) {
				Log.i(TAG, code + ": "+ error);
				updateSendedView();
			}

			@Override
			public void onProgress(int progress, String status) {
			}
		});
	}
	
	private void updateSendedView() {
		((Activity)mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				notifyDataSetChanged();
			}
		});
	}

	private class SendViewHolder {
		ImageView mAvatar;
		TextView mTime;
		TextView mContent;
		ImageView mStatus;
		ProgressBar mProgressBar;
	}
	
	private class RecvViewHolder {
		ImageView mAvatar;
		TextView mTime;
		TextView mContent;
	}
}
